<template>
  <div class="bg-white rounded-lg p-3 mx-4 w-[calc(100%-2rem)]">
    <!-- 商品小计 -->
    <div class="flex justify-between items-center py-2 border-b border-gray-100">
      <span class="text-sm text-gray-800">{{ $t("products.subtotal") }}</span>
      <span class="text-sm text-gray-800 font-medium">RM {{ formatToYuan(priceInfo && priceInfo.totalPrice) }}</span>
    </div>

    <!-- 运费金额 -->
    <div class="flex justify-between items-center py-2 border-b border-gray-100">
      <div class="flex items-center">
        <span class="text-sm text-gray-800">{{ $t("products.shippingFee") }}</span>
        <span class="text-xs text-gray-400 ml-2">{{ $t("products.freeShippingNote") }}</span>
      </div>
      <span class="text-sm text-gray-800 font-medium">RM {{ formatToYuan(priceInfo && priceInfo.deliveryPrice) }}</span>
    </div>

    <!-- YoYo币使用 -->
    <div class="py-2 border-b border-gray-100">
      <div class="flex items-center gap-2 flex-wrap">
        <van-icon name="gold-coin-o" color="#ff7a00" size="18" />
        <span class="text-xs text-gray-600 flex-1 min-w-48">
          {{ $t("products.currentYoyoCoins") }}{{ yoyoBalance }}{{ $t("products.availableYoyoCoins") }}
          <span class="text-[#ff7a00] font-bold">{{ availableYoyo }}</span>
          {{ $t("products.yoyoDiscount") }}{{ yoyoValue }}）
        </span>

        <van-icon :name="yoyoUsed ? 'checked' : 'circle'" color="#ff7a00" size="20" @click="useYoyo" />
      </div>
    </div>

    <!-- 优惠券 -->
    <div class="flex items-center gap-3 py-0 border-b border-gray-100">
      <span class="text-sm text-gray-800 min-w-15">{{ $t("products.coupon") }}</span>
      <van-field
        v-model="selectedCoupon"
        input-align="right"
        readonly
        is-link
        arrow-direction="down"
        @click="showCouponPicker = true"
        class="flex-1 pr-0" />
    </div>

    <!-- 付款总额 -->
    <div class="pt-2">
      <div class="flex justify-between items-center">
        <span class="text-base font-bold text-gray-800">{{ $t("products.totalAmount") }}</span>
        <span class="text-lg font-bold">RM {{ formatToYuan(priceInfo && priceInfo.payPrice) }}</span>
      </div>
    </div>

    <!-- 优惠券选择弹窗 -->
    <van-popup v-model="showCouponPicker" position="bottom" :style="{ height: '60%' }">
      <van-coupon-list
        disabled-title=""
        :coupons="couponOptions"
        :chosen-coupon="chosenCoupon"
        :show-exchange-bar="false"
        :show-count="false"
        @change="onCouponConfirm" />
    </van-popup>
  </div>
</template>

<script>
import { Picker, CouponCell, CouponList } from "vant"
import { getCouponList } from "@/apis/mine"
import { mapGetters } from "vuex"
import { formatToYuan } from "@/utils/common"
export default {
  name: "PaymentSummary",
  components: {
    [Picker.name]: Picker,
    [CouponCell.name]: CouponCell,
    [CouponList.name]: CouponList,
  },
  props: {
    subtotal: {
      type: Number,
      default: 376,
    },
    priceInfo: {
      type: Object,
      default: () => {},
    },
    settlementDataErrCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      yoyoBalance: 0,
      availableYoyo: 0,
      yoyoValue: 0,
      yoyoUsed: false,
      selectedCoupon: "",
      showCouponPicker: false,
      couponOptions: [],
      chosenCoupon: -1,
      formatToYuan,
    }
  },
  computed: {
    ...mapGetters({
      isZh: "lang/isZh",
      isLoggedIn: "auth/isLoggedIn",
    }),
  },
  watch: {
    settlementDataErrCode(newVal) {
      console.log('newVal :>> ', newVal);
      if (newVal == "1011000041") {
        this.useYoyo(false)
      }
      // 优惠券使用失败
      if (newVal == "1011003006") {
        this.selectedCoupon = ""
        this.chosenCoupon = -1
        setTimeout(() => {
          this.$emit("coupon-selected", "", false)
        }, 10)
      }
    },
  },
  methods: {
    useYoyo(isRefresh) {
      this.yoyoUsed = !this.yoyoUsed
      this.$emit("yoyo-used", this.yoyoUsed, isRefresh)
    },
    onCouponConfirm(value) {
      console.log("value :>> ", value)
      this.chosenCoupon = value
      this.showCouponPicker = false
      if (value == -1) {
        this.selectedCoupon = ""
        this.$emit("coupon-selected", "", true)
      } else {
        this.selectedCoupon = this.isZh ? this.couponOptions[value].name : this.couponOptions[value].nameEn
        this.$emit("coupon-selected", this.couponOptions[value].id, true)
      }
    },
    async getCouponList() {
      if (!this.isLoggedIn) {
        return
      }
      try {
        const couponList = await getCouponList()
        const list = couponList.data.list || []
        //筛选出状态为1的 并且使用门槛小于等于 subtotal
        const newCouponList = list.filter((item) => item.status == 1)

        this.couponOptions = newCouponList.map((item) => {
          return {
            name: this.isZh ? item.name : item.nameEn,
            condition: this.isZh
              ? `满${formatToYuan(item.usePrice)}元可用`
              : `Valid with a minimum spend of RM1 ${formatToYuan(item.minAmount)}`,
            startAt: item.validStartTime,
            endAt: item.validEndTime,
            valueDesc: formatToYuan(item.discountPrice),
            unitDesc: this.isZh ? "元" : "RM",
            id: item.id,
          }
        })
      } catch (error) {}
    },
  },
  created() {
    this.getCouponList()
  },
}
</script>

<style scoped>
/deep/.van-tab {
  display: none;
}
/deep/.van-tab--active {
  display: flex !important;
}
/deep/.van-tabs__line {
  display: none;
}
/deep/.van-button {
  background-color: #ff7a00;
}
/deep/.van-coupon-list__empty {
  display: flex !important;
  flex-direction: column;
  align-items: center;
}
</style>
